<template>
  <div>
    <!--    头部卡片-->
    <div class="container">
      <el-card>
        <div class="top-container">
          <div class="top-item">
            <el-button-group>
              <el-button size="mini" @click="getCurrentWeek">本周</el-button>
              <el-button size="mini" @click="getLastWeek">上周</el-button>
              <el-button size="mini" @click="getCurrentMonth">本月</el-button>
              <el-button size="mini" @click="getLastMonth">上月</el-button>
              <el-button size="mini" @click="">自定义</el-button>
            </el-button-group>
          </div>
          <div class="top-item">
            <el-date-picker
              v-model="customDate"
              type="daterange"
              placeholder="选择日期时间"
              size="mini"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </div>
          <div class="top-item">
            <span>门店：</span>
            <el-select v-model="queryForm.siteId" placeholder="请选择门店" size="mini">
              <el-option
                v-for="item in siteList"
                :key="item.siteId"
                :label="item.siteName"
                :value="item.siteId"
              >
              </el-option>
            </el-select>
          </div>
          <div class="top-item">
            <el-button size="mini" @click="allData">搜索</el-button>
          </div>
        </div>
      </el-card>
    </div>
    <!--    统计概况-->
    <div class="container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card>
            <div class="count-box">
              <div class="count-icon">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-mendianliebiao"></use>
                </svg>
              </div>
              <div class="count-info">
                <div class="count-result">
                  <div class="count-main">{{ siteTotal }}</div>
                  <div class="count-p"></div>
                </div>
                <div class="count-name">门店总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="count-box">
              <div class="count-icon">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-mendianjiankong"></use>
                </svg>
              </div>
              <div class="count-info">
                <div class="count-result">
                  <div class="count-main">{{ patrolSiteTotal.siteTotal }}</div>
                  <div class="count-p">环比 {{ patrolSiteTotal.ratio }}</div>
                </div>
                <div class="count-name">本期巡店数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="count-box">
              <div class="count-icon">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-mendiantongji"></use>
                </svg>
              </div>
              <div class="count-info">
                <div class="count-result">
                  <div class="count-main">{{ (patrolSiteTotal.siteTotal / siteTotal * 100).toFixed(1) }}%</div>
                  <div class="count-p"></div>
                </div>
                <div class="count-name">巡店覆盖率</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card>
            <div class="count-box">
              <div class="count-icon">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-mendianzichan"></use>
                </svg>
              </div>
              <div class="count-info">
                <div class="count-result">
                  <div class="count-main">{{ patrolSiteTotal.qualifyRatio }}</div>
                  <div class="count-p"></div>
                </div>
                <div class="count-name">巡检合格率</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <!--    图表-->
    <div class="container">
      <el-row>
        <el-col>
          <el-card>
            <ScoreChart :style="{height:'400px',width:'100%'}" :data="scoreData" ref="ScoreChart"></ScoreChart>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <el-card>
            <div slot="header" class="clearfix">
              <span style="font-size: 16px;font-weight: 600">门店问题量排名</span>
              <i style="float: right; padding: 3px 0;cursor: pointer" class="el-icon-more"></i>
            </div>
            <RankingChart :style="{height:'310px',width:'100%'}" :data="rankingData"></RankingChart>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header" class="clearfix">
              <span style="font-size: 16px;font-weight: 600">门店合格率</span>
              <i style="float: right; padding: 3px 0;cursor: pointer" class="el-icon-more"></i>
            </div>
            <UtilizationChart :data="utilizationData" :style="{height:'310px',width:'100%'}"></UtilizationChart>
          </el-card>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="12">
          <el-card>
            <div slot="header" class="clearfix">
              <span style="font-size: 16px;font-weight: 600">督导执行力-巡店覆盖情况</span>
              <i style="float: right; padding: 3px 0;cursor: pointer" class="el-icon-more"></i>
            </div>
            <DirectChart :data="directData" :style="{height:'310px',width:'100%'}"></DirectChart>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header" class="clearfix">
              <span style="font-size: 16px;font-weight: 600">督导执行力-任务巡店逾期情况</span>
              <i style="float: right; padding: 3px 0;cursor: pointer" class="el-icon-more"></i>
            </div>
            <TimeoutChart :data="timeoutData" :style="{height:'310px',width:'100%'}"></TimeoutChart>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import {
  queryCurrUserSite,
  queryIssueRanking, queryPatrolCoverage,
  queryPatrolSiteTotal, queryPatrolTask,
  queryRatioScore, querySiteQualifyRatio,
  querySiteTotal
} from '@/api/cruising'
import '@/assets/cruanalysis/font_2830803_y3z0492x4v/iconfont'
import ScoreChart from '@/components/Charts/ScoreChart'
import RankingChart from '@/components/Charts/RankingChart'
import UtilizationChart from '@/components/Charts/UtilizationChart'
import DirectChart from '@/components/Charts/DirectChart'
import TimeoutChart from '@/components/Charts/TimeoutChart'

export default {
  name: '',
  components: {
    ScoreChart,
    RankingChart,
    UtilizationChart,
    DirectChart,
    TimeoutChart
  },
  data() {
    // const name

    return {
      queryForm: {
        date: [],
        siteId: '',
        startTime: '',
        endTime: ''
      },
      customDate: [],
      // 门店数据
      siteList: [],
      // 门店总数
      siteTotal: 0,
      // 本期巡店数、环比、巡检合格率
      patrolSiteTotal: {},
      // 表格数据
      scoreData: [],
      // 站点排名
      rankingData: [],
      // 本店合格率
      utilizationData: {
        percentage: 0,
        data: []
      },
      // 覆盖情况
      directData: [],
      // 逾期情况
      timeoutData:[]
    }
  },
  created() {
    this.getCurrUserSite()
    this.getCurrentWeek()
  },
  mounted() {
  },
  watch: {
    customDate(newVal) {
      this.queryForm.startTime = newVal[0]
      this.queryForm.endTime = newVal[1]
    }
  },
  computed: {},
  methods: {
    // 设置本周
    setCurrentWeek() {
      // 如果为null,则格式化当前时间
      var value = Number(new Date())
      // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
      if (value.toString().length == 10) value *= 1000
      value = +new Date(Number(value))

      const one_day = 86400000 // 24 * 60 * 60 * 1000;
      const weekDate = new Date(value)
      const day = weekDate.getDay() === 0 ? 7 : weekDate.getDay() // 返回1-7,7表示周日
      // 设置时间为当天的0点
      weekDate.setHours(0, 0, 0, 0)

      //算出本周开始时间结束时间
      const week_start_time = new Date(weekDate.getTime() - (day - 1) * one_day)
      const week_end_time = new Date(weekDate.getTime() + (7 - day) * one_day)

      //格式化日期
      const filters = n => {
        return n < 10 ? (n = '0' + n) : n
      }
      const startmonth = filters(week_start_time.getMonth() + 1)
      const startDay = filters(week_start_time.getDate())
      const endmonth = filters(week_end_time.getMonth() + 1)
      const endDay = filters(week_end_time.getDate())

      const startDateTime = week_start_time.getFullYear() + '-' + startmonth + '-' + startDay
      const endDateTime = week_end_time.getFullYear() + '-' + endmonth + '-' + endDay

      this.queryForm.startTime = startDateTime
      this.queryForm.endTime = endDateTime
    },
    // 设置上周
    setLastWeek() {
      // 如果为null,则格式化当前时间
      var value = Number(new Date())
      // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
      if (value.toString().length == 10) value *= 1000
      value = +new Date(Number(value))
      const one_day = 86400000 // 24 * 60 * 60 * 1000;
      const lastWeekDate = new Date(value - 7 * one_day)
      const day = lastWeekDate.getDay() === 0 ? 7 : lastWeekDate.getDay() // 返回1-7,7表示周日
      // 设置时间为上周那天的0点
      lastWeekDate.setHours(0, 0, 0, 0)

      //算出上周开始时间结束时间
      const week_start_time = new Date(lastWeekDate.getTime() - (day - 1) * one_day)
      const week_end_time = new Date(lastWeekDate.getTime() + (7 - day) * one_day)
      //格式化日期
      const filters = n => {
        return n < 10 ? (n = '0' + n) : n
      }
      const startmonth = filters(week_start_time.getMonth() + 1)
      const startDay = filters(week_start_time.getDate())
      const endmonth = filters(week_end_time.getMonth() + 1)
      const endDay = filters(week_end_time.getDate())

      const startDateTime = week_start_time.getFullYear() + '-' + startmonth + '-' + startDay
      const endDateTime = week_end_time.getFullYear() + '-' + endmonth + '-' + endDay

      this.queryForm.startTime = startDateTime
      this.queryForm.endTime = endDateTime
    },
    // 设置本月
    setCurrentMonth() {
      // 如果为null,则格式化当前时间
      var value = Number(new Date())
      // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
      if (value.toString().length == 10) value *= 1000
      value = +new Date(Number(value))

      const targetTime = new Date(value)
      const year = targetTime.getFullYear()
      let month = targetTime.getMonth() + 1
      if (month < 10) {
        month = '0' + month
      }

      const yDate = new Date(year, month, 0)

      const startDateTime = year + '-' + month + '-' + '01' //这个月第一天
      const endDateTime = year + '-' + month + '-' + yDate.getDate() //这个月最后一天

      this.queryForm.startTime = startDateTime
      this.queryForm.endTime = endDateTime
    },
    // 设置上个月
    setLastMonth() {
      // 如果为null,则格式化当前时间
      var value = Number(new Date())
      // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
      if (value.toString().length == 10) value *= 1000
      value = +new Date(Number(value))

      // 获取上个月时间
      const targetTime = new Date(value)
      let year = targetTime.getFullYear()
      let month = targetTime.getMonth()
      if (month === 0) {
        month = 12
        year = year - 1
      }
      if (month < 10) {
        month = '0' + month
      }

      const yDate = new Date(year, month, 0)

      const startDateTime = year + '-' + month + '-' + '01' //上个月第一天
      const endDateTime = year + '-' + month + '-' + yDate.getDate() //上个月最后一天

      this.queryForm.startTime = startDateTime
      this.queryForm.endTime = endDateTime
    },
    allData() {
      this.getSiteTotal()
      this.getPatrolSiteTotal()
      this.getRatioScore()
      this.getIssueRanking()
      this.getSiteQualifyRatio()
      this.getPatrolCoverage()
      this.getPatrolTask()
    },

    // 获取本周数据
    getCurrentWeek() {
      this.setCurrentWeek()
      this.allData()
    },
    // 获取上周数据
    getLastWeek() {
      this.setLastWeek()
      this.allData()
    },
    // 获取本月数据
    getCurrentMonth() {
      this.setCurrentMonth()
      this.allData()
    },
    // 获取上月数据
    getLastMonth() {
      this.setLastMonth()
      this.allData()
    },
    // 获取门店列表
    async getCurrUserSite() {
      const res = await queryCurrUserSite()
      if (res.code !== 0) return this.$message.error(res.msg)
      this.siteList = res.data
    },
    // 获取网点总数
    async getSiteTotal() {
      const res = await querySiteTotal()
      if (res.code !== 0) return this.$message.error(res.msg)
      if (res.data === null) return this.$message.error('无数据')
      this.siteTotal = res.data
    },
    // 获取本期巡店数、环比、巡检合格率
    async getPatrolSiteTotal() {
      const res = await queryPatrolSiteTotal(this.queryForm)
      if (res.code !== 0) return this.$message.error(res.msg)
      if (res.data === null) return this.$message.error('无数据')
      this.patrolSiteTotal = res.data
    },
    // 获取得分率分布
    async getRatioScore() {
      const res = await queryRatioScore(this.queryForm)
      if (res.code !== 0) return this.$message.error(res.msg)
      if (res.data === null) return this.$message.error('无数据')
      this.scoreData = res.data.map(item => [item.createTime,item.ratioScore])
      setTimeout(()=>{
        this.$refs.ScoreChart.initChart()},0)

    },
    // 获取门店问题量排名
    async getIssueRanking() {
      const res = await queryIssueRanking(this.queryForm)
      if (res.code !== 0) return this.$message.error(res.msg)
      if (res.data === null) return this.$message.error('无数据')
      this.rankingData = res.data
    },
    // 获取门店合格率
    async getSiteQualifyRatio() {
      const res = await querySiteQualifyRatio(this.queryForm)
      if (res.code !== 0) return this.$message.error(res.msg)
      if (res.data === null) return this.$message.error('无数据')
      this.utilizationData.data = res.data.unQualifyRanking
      this.utilizationData.percentage = (res.data.siteQualifyTotal / this.siteTotal * 100).toFixed(0)
      // console.log('门店合格率',res)
    },
    //督导执行力-巡店覆盖情况
    async getPatrolCoverage() {
      const res = await queryPatrolCoverage(this.queryForm)
      if (res.code !== 0) return this.$message.error(res.msg)
      this.directData = res.data.sort(function(a, b){
        return b.coverageRatio.slice(0,1) - a.coverageRatio.slice(0,1)
      })
      // console.log('巡店覆盖情况',res)
    },
    // 督导执行力-任务巡店逾期情况
    async getPatrolTask() {
      const res = await queryPatrolTask(this.queryForm)
      if (res.code !== 0) return this.$message.error(res.msg)
      this.timeoutData = res.data.sort(function(a, b){
        return b.overdueRatio.slice(0,1) - a.overdueRatio.slice(0,1)
      })
      // console.log('任务巡店逾期情况',res)
    },
  }
}
</script>

<style lang="scss" scoped>
.icon {
  width: 2em;
  height: 2em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.el-card {
  margin-bottom: 10px !important;
}

.count-box {
  display: flex;
  align-items: center;
  padding: 0 10px;

  .count-icon {
    margin-right: 20px;
  }

  .count-info {
    .count-result {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .count-main {
        font-size: 26px;
        margin-right: 10px;
      }

      .count-p {
        font-size: 12px;
        color: green;
      }
    }

    .count-name {
      font-size: 12px;
      color: #7c7c7c;
    }
  }
}

.top-container {
  display: flex;
  align-items: center;

  .top-item {
    font-size: 12px;
    margin-right: 20px;
  }
}
</style>
